from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse,HttpResponseRedirect
from .models import Question,Choice
from django.urls import reverse
# Create your views here.
def index(request):
    latest_question_list = Question.objects.all()
    #latest_question_list = [question.question_text for question in question_set] 
    #return HttpResponse(str(latest_question_list))
    return render(request,'polls/index.html',{'latest_question_list':latest_question_list})
'''
def detail(request,question_id):    
    #question = Question.objects.get(pk = question_id)
    question = Question.objects.filter(pk = question_id)
    if question:
        return render(request,'polls/detail.html',{'question':question[0]})
    else:
        return HttpResponse("确定没有这个问题！")
'''        
def detail(request,question_id):
    question = get_object_or_404(Question,pk = question_id)
    return render(request,'polls/detail.html',{'question':question})
'''
def detail(request,question_id):
    try:
        question = Question.objects.get(pk = question_id)
    except Question.DoesNotExist:
        return HttpResponse("没有这个问题")
    else:
        return render(request,'polls/detail.html',{'question':question})
'''
    
def vote(request,question_id):
    question = Question.objects.get(pk = question_id)
    try:
        x = request.POST
        print(x)
        choice_id = x['choice']
        
        selected_choice = Choice.objects.get(pk = choice_id)
        print(selected_choice)
        #return HttpResponse(selected_choice)
    except KeyError:
        context = {'question':question,'error':'请选择一个选项',}
        return render(request,'polls/detail.html',context)
                      #'question':question,
                       #'error_message':"You didn't select a choice.",})
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results',args = (question.id,)))
    
def results(request,question_id):
    question = Question.objects.get(pk = question_id)
    context = {'question':question}
    return render(request,'polls/results.html',context)





